from urllib import request
from urllib import parse
import urllib
# ---------------------------------get--------------------------
# -------------------常规请求-----------------------------------
with request.urlopen("https://api.douban.com/v2/book/2129650") as f:
    data = f.read()
    print("Status:", f.status, f.reason)
    for k, v in f.getheaders():
        print("%s : %s" % (k, v))
    print(data.decode("utf-8"))
# -----------------------伪装请求-------------------------------------
req = request.Request("http://www.douban.com/")
req.add_header("User-Agent", "Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit"
                             "/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25")
with request.urlopen(req) as ft:
    data2 = ft.read()
    print("Status:", ft.status, ft.reason)
    for k, v in ft.getheaders():
        print("%s : %s" % (k, v))
    print(data2.decode("utf-8"))
# ----------------------------------post----------------------------
print("Login weibo ...")
email = input("请输入Email地址：")
passwd = input("请输入密码：")
login_data = parse.urlencode({
    'username': email,
    'password': passwd,
    'entry': 'mweibo',
    'client_id': '',
    'savestate': '1',
    'ec': '',
    'pagerefer': 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F'
})
req2 = request.Request("https://weibo.com/")
req2.add_header('Origin', 'https://passport.weibo.cn')
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit'
                             '/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry='
                          'mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')
with request.urlopen(req2, data=login_data.encode("utf-8")) as ft2:
    print("Status:", ft2.status, ft2.reason)
    for k, v in ft2.getheaders():
        print("%s : %s" % (k, v))
    print("Html:", ft2.read())
# ----------------------------------使用代理----------------------------------------------------------------------------
proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
with opener.open('http://www.example.com/login.html') as f:
    pass
